package com.satoken.Controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.satoken.Entity.CodeEnum;
import com.satoken.Entity.Result;
import com.satoken.Entity.Token;
import com.satoken.Service.UserService;
import com.satoken.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {
    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public String doLogin(@RequestBody User u) {
        if(userService.login(u)){
            StpUtil.login(u.getUsername(),"PC");
            SaTokenInfo token = StpUtil.getTokenInfo();
            return  JSON.toJSONString(new Result(CodeEnum.OK.getCode(),CodeEnum.OK.getMsg(),new Token(token.getTokenName(),token.getTokenValue())));
        }else return JSON.toJSONString(new Result(CodeEnum.ACCOUNT_ERROR.getCode(),CodeEnum.ACCOUNT_ERROR.getMsg(),null));
    }
    @RequestMapping("/register")
    public String doRegister(@RequestBody User u) {
        if(userService.register(u)){
            StpUtil.login(u.getUsername(),"PC");
            SaTokenInfo token = StpUtil.getTokenInfo();
            return  JSON.toJSONString(new Result(CodeEnum.OK.getCode(),CodeEnum.OK.getMsg(),new Token(token.getTokenName(),token.getTokenValue())));
        }else return JSON.toJSONString(new Result(CodeEnum.ACCOUNT_ERROR.getCode(),CodeEnum.ACCOUNT_ERROR.getMsg(),null));
        //SaManager.getSaTokenContext();
    }
    @RequestMapping("/isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }
}
